using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using DesktopHelper.Data;
using DesktopHelper.Models;

namespace DesktopHelper.ViewModels
{
    public class MainViewModel : INotifyPropertyChanged
    {
        private readonly ILogger<MainViewModel> _logger;
        private readonly DatabaseService _databaseService;
        
        private List<ClipboardItem> _allItems = new();
        private string _searchText = string.Empty;

        public ObservableCollection<ClipboardItem> TextItems { get; } = new();
        public ObservableCollection<ClipboardItem> ImageItems { get; } = new();
        public ObservableCollection<ClipboardItem> FileItems { get; } = new();

        private ClipboardItem? _selectedTextItem;
        private ClipboardItem? _selectedImageItem;
        private ClipboardItem? _selectedFileItem;

        public ClipboardItem? SelectedTextItem
        {
            get => _selectedTextItem;
            set => SetProperty(ref _selectedTextItem, value);
        }

        public ClipboardItem? SelectedImageItem
        {
            get => _selectedImageItem;
            set => SetProperty(ref _selectedImageItem, value);
        }

        public ClipboardItem? SelectedFileItem
        {
            get => _selectedFileItem;
            set => SetProperty(ref _selectedFileItem, value);
        }

        public string SearchText
        {
            get => _searchText;
            set
            {
                if (SetProperty(ref _searchText, value))
                {
                    FilterItems(value);
                }
            }
        }

        public int TotalItemCount => _allItems.Count;

        public MainViewModel(ILogger<MainViewModel> logger, DatabaseService databaseService)
        {
            _logger = logger;
            _databaseService = databaseService;
        }

        public async Task LoadDataAsync()
        {
            try
            {
                _logger.LogDebug("开始加载剪贴板历史数据");
                
                _allItems = await _databaseService.GetClipboardHistoryAsync(1000);
                
                FilterItems(_searchText);
                
                OnPropertyChanged(nameof(TotalItemCount));
                
                _logger.LogInformation("已加载 {Count} 条历史记录", _allItems.Count);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加载数据失败");
                throw;
            }
        }

        public void FilterItems(string? searchText)
        {
            try
            {
                var filtered = string.IsNullOrWhiteSpace(searchText) 
                    ? _allItems 
                    : _allItems.Where(item => 
                        (item.Content?.Contains(searchText, StringComparison.OrdinalIgnoreCase) ?? false) ||
                        (item.Type.ToString().Contains(searchText, StringComparison.OrdinalIgnoreCase)));

                // 清空集合
                TextItems.Clear();
                ImageItems.Clear();
                FileItems.Clear();

                // 按类型分类
                foreach (var item in filtered)
                {
                    switch (item.Type)
                    {
                        case ClipboardDataType.Text:
                            TextItems.Add(item);
                            break;
                        case ClipboardDataType.Image:
                            ImageItems.Add(item);
                            break;
                        case ClipboardDataType.File:
                            FileItems.Add(item);
                            break;
                    }
                }

                _logger.LogDebug("筛选完成: 文本 {TextCount}, 图片 {ImageCount}, 文件 {FileCount}",
                    TextItems.Count, ImageItems.Count, FileItems.Count);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "筛选数据失败");
            }
        }

        public async Task DeleteItemAsync(ClipboardItem item)
        {
            try
            {
                await _databaseService.DeleteClipboardItemAsync(item.Id);
                
                _allItems.Remove(item);
                TextItems.Remove(item);
                ImageItems.Remove(item);
                FileItems.Remove(item);
                
                OnPropertyChanged(nameof(TotalItemCount));
                
                _logger.LogDebug("已删除剪贴板项目: {Id}", item.Id);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除项目失败: {Id}", item.Id);
                throw;
            }
        }

        public async Task DeleteItemsAsync(IEnumerable<ClipboardItem> items)
        {
            try
            {
                var itemList = items.ToList();
                
                foreach (var item in itemList)
                {
                    await _databaseService.DeleteClipboardItemAsync(item.Id);
                    
                    _allItems.Remove(item);
                    TextItems.Remove(item);
                    ImageItems.Remove(item);
                    FileItems.Remove(item);
                }
                
                OnPropertyChanged(nameof(TotalItemCount));
                
                _logger.LogDebug("已删除 {Count} 个剪贴板项目", itemList.Count);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量删除项目失败");
                throw;
            }
        }

        public async Task ClearAllHistoryAsync()
        {
            try
            {
                // 删除所有项目
                foreach (var item in _allItems.ToList())
                {
                    await _databaseService.DeleteClipboardItemAsync(item.Id);
                }
                
                _allItems.Clear();
                TextItems.Clear();
                ImageItems.Clear();
                FileItems.Clear();
                
                OnPropertyChanged(nameof(TotalItemCount));
                
                _logger.LogInformation("已清空所有剪贴板历史记录");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "清空历史记录失败");
                throw;
            }
        }

        public event PropertyChangedEventHandler? PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        protected bool SetProperty<T>(ref T field, T value, [CallerMemberName] string? propertyName = null)
        {
            if (EqualityComparer<T>.Default.Equals(field, value))
                return false;

            field = value;
            OnPropertyChanged(propertyName);
            return true;
        }
    }
}